import { SchemaManage } from '@/components/SchemaComponent';
import React, { useRef, useState, useMemo } from 'react';
import { connect } from 'umi';
import { ISourceIntentionAPI } from '../common/type';
import { UpdateModal } from './UpdateModal';
import { SourceManageServices } from '../services';
import { history } from 'umi';
import { getTableColumns } from '../mconfig';
import { DetailsDrawer } from './DetailsDrawer';
import '../common/styles.less';
import { getKeyRouter, getTenantID } from '@/utils';
import { PlusOutlined } from '@ant-design/icons';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import { ILoadMapTypeAll } from '@/common';
import PublishModal from './PublishModal';
import { CancelModal } from '@/components/CancelTextModal';

const SourceIntentionManageView: React.FC<ISourceIntentionAPI.ISourceIntentionView> = ({ curRes, locationProps }) => {
  /**管理页services*/
  const { data, loading, searchList, pagination, reloadRequest, manageTableParams } = SourceManageServices(curRes);

  /**是否显示Update弹窗*/
  const [updateModal, setUpdateModal] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
    title: '',
  });

  /**是否显示Detail的抽屉*/
  const [isShowDetail, setIsShowDetail] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
  });

  /**作废弹窗*/
  const [isShowCancelModal, setIsShowCancelModal] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
  });

  /**头部权限切换*/
  const switchList: ISourceIntentionAPI.IManageTabsSwitchType = useMemo(() => {
    return [];
  }, [curRes]);

  /**撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({});

  /**切换头部方法*/
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    reloadRequest({ ...params, ...searchValues });
  };

  /**重置方法*/
  const onReset = (reqParams: ISourceIntentionAPI.ITableRequestType) => {
    reloadRequest({ ...reqParams });
  };

  /**搜索方法*/
  const onSearch = (reqParams: ISourceIntentionAPI.ITableRequestType) => {
    reloadRequest({ ...reqParams });
  };

  /**刷新管理页面的办法*/
  const reloadManage = () => {
    reloadRequest({ ...manageTableParams });
  };

  /**分页方法*/
  const onPageChange = (current: any, pageSize: any, params: any) => {
    reloadRequest({ pageSize, current, ...params });
  };
  // 公布弹框显示隐藏
  const [publish, setPublish] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
  });
  /**Table操作列的事件池*/
  const getTableOperateFuncs: ISourceIntentionAPI.ISourceTableActionType = {
    /**详情按钮*/
    onView(record) {
      let info = { mpurchaseSourceIntents: [{ id: record?.id }] };
      history.push({
        pathname: `/purchaseSourceIntentController/getIntentById/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          info: info,
          operateType: 'Manage',
          type: 'view',
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onEdit(record) {
      let info = { mpurchaseSourceIntents: [{ id: record?.id }] };
      history.push({
        pathname: `/purchaseSourceIntentController/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          info: info,
          operateType: 'Manage',
          type: 'edit',
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onInvalid: (record) => {
      setInvalidState({ isShow: true, resObj: record });
    },
    onPublish: (record) => {
      setPublish({ isShow: true, resObj: record });
    },
    onCancel: (record) => setIsShowCancelModal({ isShow: true, resObj: record }),
  };

  /**Table的columns集合*/
  const getTableColumn: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, getTableOperateFuncs);
  }, [curRes]);

  /**新增操作按钮*/
  const actionList: ISourceIntentionAPI.IActionList = useMemo(() => {
    return [
      {
        title: '添加',
        visible: curRes?.['/purchaseSourceIntentController/add'] || false,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          history.push({
            pathname: `/purchaseSourceIntentController/add/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              info: {},
              operateType: 'add',
              type: 'add',
              returnPathName: locationProps?.pathname,
            },
          });
        },
      },
    ];
  }, [curRes]);

  return (
    <>
      <div
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <SchemaManage
          ref={useRef()}
          searchProps={{
            switchList,
            searchList,
            onSwitch,
            onReset,
            onSearch,
          }}
          actionList={actionList}
          tableProps={{
            columns: getTableColumn,
            dataSource: data?.rows, //mockData
            rowKey: 'id',
            loading: loading,
            pagination: pagination as any,
            onPageChange: onPageChange,
          }}
        />
        {/**新增编辑Modal*/}
        {updateModal?.isShow && (
          <>
            <UpdateModal
              curRes={curRes}
              updateState={updateModal}
              onClose={() => {
                setUpdateModal({
                  isShow: false,
                  resObj: {},
                  title: '',
                });
              }}
              reloadManage={reloadManage}
            />
          </>
        )}
        {/* 详情抽屉 */}
        <DetailsDrawer
          isShowDetail={isShowDetail}
          onClose={() => {
            setIsShowDetail({
              isShow: false,
              resObj: {},
            });
          }}
        />

        {/* 撤销 */}
        {invalidState?.isShow && (
          <RevokeModal
            resObj={invalidState?.resObj}
            revokeRequestUrl={'/purchaseSourceIntentController/invalid'}
            onClose={() => setInvalidState({})}
            reqBody={{ state: `${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}1000` }}
            modalTip={
              <div style={{ color: '#000' }}>
                确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.purchProjectName}</span>】的审核, 撤销后可重新提交！
              </div>
            }
            reloadRequest={reloadManage}
          />
        )}
        {/** 公布弹窗 */}
        {publish?.isShow && (
          <PublishModal
            onClose={() => {
              setPublish({
                isShow: false,
                resObj: {},
              });
              reloadManage();
            }}
            publish={publish}
          />
        )}
        {/* 作废弹窗 */}
        {isShowCancelModal?.isShow && (
          <CancelModal
            checkRows={isShowCancelModal?.resObj}
            cancelTypeDic={ILoadMapTypeAll.INTENTION_CANCEL}
            cancelFormTypeRequired={true}
            cancelFormReasonRequired={true}
            modalTitle={'作废意向公开'}
            cancelText={isShowCancelModal?.resObj?.intentName || null}
            cancelRequestUrl={'/purchaseSourceIntentController/cancel'}
            reloadManage={reloadManage}
            cancelRequestType="PUT"
            cancelRequestBody={{ state: `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1003` }}
            onClose={() => setIsShowCancelModal({})}
          />
        )}
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(SourceIntentionManageView);
